package vn.codespot.hms.task;

import vn.codespot.hms.api.Service;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.widget.Toast;

public abstract class AbstractTask extends AsyncTask<Void, Void, Void> {
    private Context mCtx;

    private String mProcessTitle;

    private String mCancelMsg;

    private ProgressDialog mDialog;

    private boolean isCancel;

    protected Service mService;

    public AbstractTask(Context context, String processTitle, String cancelMessage) {
        mService = new Service();
        mCtx = context;
        mProcessTitle = processTitle;
        mCancelMsg = cancelMessage;
        isCancel = true;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {
        OnCancelListener cancelListener = new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface arg0) {
                mService.cancelRequesting();
                if (isCancel) {
                    Toast.makeText(mCtx, mCancelMsg, Toast.LENGTH_SHORT).show();
                }
            }
        };
        mDialog = ProgressDialog.show(mCtx, mProcessTitle, "Processing...", true, true, cancelListener);
        mDialog.setCanceledOnTouchOutside(true);
    }

    @Override
    protected Void doInBackground(Void... params) {
        executes();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        isCancel = false;
        mDialog.cancel();
        finish();
    }

    protected abstract void executes();

    protected abstract void finish();
}
